package newtank.network.client.handler;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import newtank.TankClientFrame;
import newtank.data.MoveOperatorSignal;
import newtank.data.assistant.SyncData;
import newtank.utils.OperatorUtils;
import newtank.view.PaintView;
import server.GpcRequest;
import server.netty.GpcDataPackage;

/**
 * @author lijiahao
 * @since 2022/3/17
 */
@AllArgsConstructor
public class MoveDataHandler implements DataHandler<MoveOperatorSignal> {

    private final TankClientFrame tankClientFrame;

    @Override
    public MoveOperatorSignal decodePackage(GpcDataPackage gpcDataPackage) {
        GpcRequest gpcRequest = gpcDataPackage.getRouteRequest();
        String sync = gpcRequest.getHeader(SyncData.SYNC_DATA);
        SyncData syncData = JSONObject.parseObject(sync, SyncData.class);
        return new MoveOperatorSignal(gpcDataPackage.getUnique(),
                gpcRequest.getHeader("move_type"),
                gpcRequest.getHeader("move_code"),
                syncData);
    }

    @Override
    public void handle(GpcDataPackage gpcDataPackage) {
        MoveOperatorSignal signal = decodePackage(gpcDataPackage);
        String tankId = signal.getUnique();
        String type = signal.getType();
        PaintView paintView = tankClientFrame.getView(tankId);
        if(paintView == null) {
            throw new NullPointerException();
        }
        OperatorUtils.operatorView(paintView, type);
    }

    @Override
    public boolean support(GpcDataPackage gpcDataPackage) {
        return gpcDataPackage != null && gpcDataPackage.getCode() == 10;
    }
}
